package com.aaa.controller;

import cn.hutool.core.util.ObjectUtil;
import com.aaa.controller.BaseController;
import com.aaa.entity.Result;
import com.aaa.entity.systemmanage.User;
import com.aaa.service.systemmanage.MenuService;
import com.aaa.service.systemmanage.UserService;
import com.aaa.utils.Password;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author ：XiaoxXuan
 * @date ：Created in 2022.08.05 17:17
 * @description：
 * @modified By：
 */
@RestController
@RequestMapping("/login")
public class LoginController extends BaseController {

    @Autowired
    UserService userService;

    @Autowired
    MenuService menuService;

    @RequestMapping(method = RequestMethod.POST,value = "/loginVerify.do")
    public Result loginVerify(User user, HttpSession session){
        String username = user.getUsername();
        String password = user.getPassword();
        //根据用户名去数据库查找
        User newUser = userService.queryUserinfoByUsername(username);
        if(ObjectUtil.isEmpty(newUser)){
            //用户不存在
            return  fail("用户"+ user.getUsername()+"不存在");
        }else {
            //用户存在,
            // 1、根据用户将用户的盐值和密文查询出来
            String sqlsalt = newUser.getSalt();
            //数据库的密文
            String sqlpassword = newUser.getPassword();
            // 2、将明文密码加密之后跟第一步的密文对比，一致就是登录成功
            String makePasswordSalt = Password.makePasswordSalt(password, sqlsalt);
            if(makePasswordSalt.equals(sqlpassword)){
                //登录成功，根据用户名，查询对应的所有的菜单
                Map<String, Object> map = menuService.queryMenuByUsername(username);
                session.setAttribute("menuListMap",map);
                session.setAttribute("user",newUser);
                return   success("登录成功");
            }else {
                return  fail("密码错误");
            }
        }
    }


    @RequestMapping("logout.do")
    public ModelAndView logout(ModelAndView modelAndView, HttpSession session){
        //注销，需要销毁session
        session.invalidate();
        //跳转到登录页面
        modelAndView.setViewName("login");
        return  modelAndView;
    }



}